//
//  MapViewController.m
//  HappyStore
//
//  Created by 李小辉 on 16/9/12.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "MapViewController.h"
#import <BaiduMapAPI_Map/BMKMapView.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
@interface MapViewController ()<BMKMapViewDelegate, BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate>

@property (strong, nonatomic) BMKMapView *mapView;
@property (strong, nonatomic) BMKLocationService *locService;
@property (strong, nonatomic) BMKPointAnnotation* pointAnnotation;
@property (strong, nonatomic) BMKGeoCodeSearch* geocodesearch;
@property (strong, nonatomic) UITextField *addressTextField;
@property (strong, nonatomic) NSMutableDictionary *addressInfo;
@end

@implementation MapViewController
- (NSMutableDictionary *)addressInfo{
    if (!_addressInfo) {
        _addressInfo = [NSMutableDictionary dictionary];
    }
    return _addressInfo;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    self.mapView.delegate = self;// 此处记得不用的时候需要置nil，否则影响内存的释放
     self.locService.delegate = self;
    self.geocodesearch.delegate = self;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
    
    //找出导航栏的下边的黑线
    UIImageView *navBarHairlineImageView = [NaviBarLine findHairlineImageViewUnder:self.navigationController.navigationBar];
    navBarHairlineImageView.hidden = NO;
    navBarHairlineImageView.alpha = 0.5f;
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear: animated];
    self.mapView.delegate = nil;// 不用时，置nil
    self.locService.delegate = nil;
    self.geocodesearch.delegate = nil;
    
    
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    //找出导航栏的下边的黑线
    UIImageView *navBarHairlineImageView = [NaviBarLine findHairlineImageViewUnder:self.navigationController.navigationBar];
    navBarHairlineImageView.hidden = YES;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = @"活动地点";
    titleLabel.textColor = RGB(45, 45, 45);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    
    // 设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"];
    self.navigationItem.leftBarButtonItem = leftItem;
    //初始化BMKLocationService
    self.locService = [[BMKLocationService alloc]init];
   
    //启动LocationService
    [self.locService startUserLocationService];
    
    
    self.mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 64, screenW, screenH - 90 - 64)];
    //普通态
    //以下_mapView为BMKMapView对象
    _mapView.showsUserLocation = NO;//先关闭显示的定位图层
    _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
//    _mapView.showsUserLocation = YES;//显示定位图层
    //检索
    self.geocodesearch = [[BMKGeoCodeSearch alloc]init];
    
    [_mapView setZoomLevel:14];
    

    //
//    UITapGestureRecognizer
    //视图下部
    self.view.backgroundColor = [UIColor whiteColor];
    

    UIView *downView = [[UIView alloc] initWithFrame:CGRectMake(0, screenH-90, screenW, 90)];
    downView.backgroundColor = RGB(247, 247, 247);
    UIButton *okButton = [[UIButton alloc] initWithFrame:CGRectMake(22, downView.height - 8-40, downView.width-22 * 2, 40)];
    [okButton setBackgroundColor:RGB(32, 165, 240)];
    [okButton setTitle:@"确 定" forState:UIControlStateNormal];
    [okButton setTintColor:[UIColor whiteColor]];
    okButton.titleLabel.font = [UIFont systemFontOfSize:15];
    okButton.layer.cornerRadius = 4.0;
    okButton.layer.masksToBounds = YES;
    [okButton addTarget:self action:@selector(clickOkBtn) forControlEvents:UIControlEventTouchUpInside];
    self.addressTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 8, screenW, 30)];
    self.addressTextField.backgroundColor = [UIColor whiteColor];
    self.addressTextField.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.mapView];
    [downView addSubview:self.addressTextField];
    [downView addSubview:okButton];
    [self.view addSubview:downView];

    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}


#pragma mark - 确定
//确定
- (void)clickOkBtn{
    if ([self.addressInfo[@"address"] isEqualToString:self.addressTextField.text]) {
        //没手动填写
    }else{
        self.addressInfo[@"address"] = self.addressTextField.text;
        self.addressInfo[@"province"] = @"";
        self.addressInfo[@"city"] = self.addressTextField.text;
        self.addressInfo[@"district"] = @"";
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"mapAddress" object:self userInfo:self.addressInfo];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}

//实现相关delegate 处理位置信息更新
//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
//    NSLog(@"heading is %@",userLocation.heading);
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //大头针
    if (!self.pointAnnotation) {
        self.pointAnnotation = [[BMKPointAnnotation alloc]init];
        [self.mapView addAnnotation:self.pointAnnotation];

        
        CLLocationCoordinate2D coor;
        coor.latitude = userLocation.location.coordinate.latitude;
        coor.longitude = userLocation.location.coordinate.longitude;
        self.pointAnnotation.coordinate = coor;
        self.mapView.centerCoordinate = userLocation.location.coordinate;
    }


 
    [_mapView updateLocationData:userLocation];
    
//    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
}


//反向地理编码结果
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
//    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
//    [_mapView removeAnnotations:array];
//    array = [NSArray arrayWithArray:_mapView.overlays];
//    [_mapView removeOverlays:array];
    if (error == 0) {
        NSString* titleStr;
        titleStr = @"反向地理编码";
        self.addressInfo[@"address"] = result.address;
        self.addressInfo[@"province"] = result.addressDetail.province;
        self.addressInfo[@"city"] = result.addressDetail.city;
        self.addressInfo[@"district"] = [NSString stringWithFormat:@"%@%@%@",result.addressDetail.district,result.addressDetail.streetName,result.addressDetail.streetNumber];
        
        
        self.addressTextField.text = result.address;

    }
}

/**
 *地图渲染每一帧画面过程中，以及每次需要重绘地图时（例如添加覆盖物）都会调用此接口
 *@param mapview 地图View
 *@param status 此时地图的状态
 */
- (void)mapView:(BMKMapView *)mapView onDrawMapFrame:(BMKMapStatus*)status{
    self.pointAnnotation.coordinate = status.targetGeoPt;
}

/**
 *地图区域改变完成后会调用此接口
 *@param mapview 地图View
 *@param animated 是否动画
 */
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    //反编码
        CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
        pt = (CLLocationCoordinate2D){mapView.region.center.latitude,mapView.region.center.longitude};
        BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
        reverseGeocodeSearchOption.reverseGeoPoint = pt;
        BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
        if(flag)
        {
            NSLog(@"反geo检索发送成功");
        }
        else
        {
            NSLog(@"反geo检索发送失败");
        }
    

}


/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    self.pointAnnotation = [[BMKPointAnnotation alloc]init];
    [self.mapView addAnnotation:self.pointAnnotation];
//    NSLog(@"location error");
}

- (void)dealloc {
    if (_geocodesearch != nil) {
        _geocodesearch = nil;
    }
    if (_mapView) {
        _mapView = nil;
    }
}
@end
